<template>
  <div class="container">
    <div class="table-data">
      <el-card class="box-card">
        <el-row
          style="
            margin-bottom: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
          "
        >
          <el-col :span="10">
            <!-- 新增 -->
            <el-button type="warning" icon="el-icon-plus" size="small" @click="richtext">新增</el-button>

            <!-- 编辑 -->
            <!-- <el-button type="primary" icon="el-icon-edit" size="small" disabled
              >修改</el-button
            >-->

            <!-- 删除 -->
            <el-button type="danger" icon="el-icon-delete" size="small" @click="deletemore">删除</el-button>
          </el-col>

          <el-col :span="4" :offset="10">
            <el-input placeholder="请输入内容">
              <template slot="append">
                <el-button slot="append" icon="el-icon-search"></el-button>
              </template>
            </el-input>
          </el-col>
        </el-row>
        <!-- 富文本编辑器-添加 -->
        <div v-if="EDIshow" class="editorclass">
          <h1 class="title">添加富文本</h1>
          <el-form :model="form" class="editorform">
            <el-form-item label="标题" :label-width="formLabelWidth">
              <el-input v-model="form.title" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="封面" :label-width="formLabelWidth" prop="pic">
              <!-- 上传图片 -->
              <!-- http://api_dev.wanxikeji.cn/api/saveFile -->
              <el-upload
                class="upload-demo"
                ref="upload"
                action="http://api_dev.wanxikeji.cn/api/saveFile"
                :http-request="uploadFile"
                :on-change="handleChange"
                :on-remove="handleRemove"
                :show-file-list="false"
                :limit="1"
                :on-exceed="handleExceed"
              >
                <el-button slot="trigger" size="small" type="success">上传图片</el-button>
                <el-form-item label prop="img" v-if="form.pic!=''">
                  <img :src="form.pic" width="100px" style="height:100px" />
                </el-form-item>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
              </el-upload>
            </el-form-item>
            <el-form-item label="描述" :label-width="formLabelWidth" class="txtarea">
              <el-input type="textarea" v-model="form.describe" autocomplete="off"></el-input>
            </el-form-item>
          </el-form>
          <!-- 富文本编辑器 -->
          <editors></editors>
          <div class="richbtn">
            <el-button type="danger" icon="el-icon-edit-outline" @click="offrichtext">取消</el-button>
            <el-button type="success" icon="el-icon-edit-outline" @click="addrichtext">提交</el-button>
          </div>
        </div>
        <!-- 富文本编辑器-修改 -->
        <div v-if="EDIchange" class="editorclass">
          <h1 class="title">信息修改</h1>
          <el-form :model="form" class="editorform">
            <el-form-item label="编号" :label-width="formLabelWidth">
              <el-input v-model="changeform.id" autocomplete="off" disabled></el-input>
            </el-form-item>
            <el-form-item label="标题" :label-width="formLabelWidth">
              <el-input v-model="changeform.title" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="封面" :label-width="formLabelWidth">
              <!-- 上传图片 -->
                <!-- :on-success="deletebefore2" -->
              <el-upload
                class="upload-demo"
                ref="upload2"
                action="http://api_dev.wanxikeji.cn/api/saveFile"
                :on-change="handleChange2"
                :on-remove="handleRemove2"
                :http-request="uploadFile2"
                :limit="1"
                :on-exceed="handleExceed2"
                :show-file-list="false"
              >
                <el-button slot="trigger" size="small" type="success">上传图片</el-button>
                <el-form-item label prop="img">
                  <img :src="changeform.pic" width="100px" style="height:100px" />
                </el-form-item>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
              </el-upload>
            </el-form-item>
            <el-form-item label="描述" :label-width="formLabelWidth" class="txtarea">
              <el-input type="textarea" v-model="changeform.describe" autocomplete="off"></el-input>
            </el-form-item>
          </el-form>
          <!-- 富文本编辑器 -->
          <div class="editor-box">
            <editors :pid="5" class="myeditor"></editors>
          </div>
          

          <div class="richbtn">
            <el-button type="danger" icon="el-icon-edit-outline" @click="offchangetext">取消</el-button>
            <el-button type="success" icon="el-icon-edit-outline" @click="changetext">提交</el-button>
          </div>
        </div>
        <el-table
          v-if="TABLEshow"
          :data="dataShow"
          stripe
          border
          @selection-change="selectionchange"
          style="width: 100%"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <!-- <el-table-column label="token" prop="token"> </el-table-column> -->
          <el-table-column label="编号" prop="id"></el-table-column>
          <el-table-column label="标题" prop="title"></el-table-column>
          <el-table-column label="封面" prop="pic" width="150">
            <template slot-scope="scope">
              <el-image :src="scope.row.pic" width="50px" style="height:50px"></el-image>
            </template>
          </el-table-column>
          <el-table-column label="描述" prop="describe"></el-table-column>
          <!-- <el-table-column label="作品内容" prop="info"> </el-table-column> -->
          <el-table-column label="操作" width="220px">
            <template slot-scope="scope">
              <el-button
                size="mini"
                icon="el-icon-edit-outline"
                @click="handleEdit(scope.$index, scope.row)"
              ></el-button>
              <el-button
                size="mini"
                type="danger"
                icon="el-icon-delete"
                @click="handleDelete(scope.$index, scope.row)"
              ></el-button>
              <el-button size="mini" type="danger" @click="forbiddendata(scope.$index, scope.row)">
                {{
                alldataShow[alldataShow.indexOf(scope.row)].status == 3
                ? isforbidden
                : forbidden
                }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div v-if="TABLEshow">
          <el-pagination
            style="margin-top: 20px"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage4"
            :page-sizes="[4, 6, 8, 10]"
            :page-size="pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="arraylength"
          ></el-pagination>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import editors from "../wangeditor";
export default {
  components: {
    editors,
  },
  data() {
    return {
      EDIshow: false,
      TABLEshow: true,
      EDIchange: false,
      namesearch: "",
      imgUrl: "",
      form: {
        id: "",
        title: "",
        pic: "",
        describe: "",
      },
      changeform: {
        id: "",
        title: "",
        pic: "",
        describe: "",
      },
      dataShow: [],
      alldataShow: [],
      formLabelWidth: "120px",
      // fileList: [{ name: "", url: "" }],
      currentPage4: 1,
      arraylength: 0,
      pagesize: 4,
      page: 1,
      moment: [],
      deleteall: [],
      changearr: [],
      indexnum: 0,
      imgfile: "",
      localimg: true,
      lineimg: false,
      lineimgchange: true,
      localimgchange: false,
      // forbidden: [],
      isforbidden: "已禁用",
      forbidden: "禁用",
      banstatus: false,
    };
  },
  methods: {
    //   添加按钮
    richtext() {
      this.EDIchange = false;
      this.EDIshow = true;
      this.TABLEshow = false;
      this.form = {
        id: "",
        title: "",
        pic: "",
        describe: "",
      };
    },
    // 取消添加
    offrichtext() {
      this.EDIshow = false;
      this.TABLEshow = true;
    },
    // 上传本地图片
    onlocalimg() {
      this.localimg = true;
      this.lineimg = false;
      this.lineimgchange = false;
      this.localimgchange = true;
      this.form.pic = "";
      this.changeform.pic = "";
    },
    uploadFile(file) {
      let formDatas = new FormData();
      formDatas.append('file', file.file);
      this.$http.post('/api/saveFile', formDatas).then(res => {
        // console.log('封面',res)

        if (res.data.msg == '保存成功') {
          this.form.pic = `http://api_dev.wanxikeji.cn/${res.data.data}`
        }

      })
    },
    uploadFile2(file) {
      let formDatas = new FormData();
      console.log(file.file);
      formDatas.append('file', file.file);
      console.log(formDatas);
      console.log(this.changeform.pic);
      this.$http.post('/api/saveFile', formDatas).then(res => {
        // console.log('封面',res)

        if (res.data.msg == '保存成功') {
          console.log(12345);
          this.changeform.pic = `http://api_dev.wanxikeji.cn/${res.data.data}`
        }

      })
    },
    // 上传网上图片
    // 添加图片
    // beforeAvatarUpload(file) {
    //   console.log("file", file);
    //   this.imgfile = file;
    // },
    handleChange(file, fileList) {
      console.log("changefile", file);
      // this.imgfile = file.raw;
      if (file.name.split('.')[1] == 'mp4' || file.name.split('.')[1] == 'gif' || file.name.split('.')[1] == 'jpg' || file.name.split('.')[1] == 'png' || file.name.split('.')[1] == 'jpeg') {
        console.log(1)
      }
      else {

        this.handleRemove(file, fileList)
      }
    },
    handleChange2(file, fileList) {
      // console.log("changefile", file);
      // this.imgfile = file.raw;
      if (file.name.split('.')[1] == 'mp4' || file.name.split('.')[1] == 'gif' || file.name.split('.')[1] == 'jpg' || file.name.split('.')[1] == 'png' || file.name.split('.')[1] == 'jpeg') {
        console.log(1)
      }
      else {

        // this.handleRemove2(file,fileList)
      }
    },
    // deletebefore2(response, file, fileList) {
    //   console.log(3333);
    //   this.$refs.upload2.clearFiles();
    // },
    handleExceed(files, fileList) {
      this.handleRemove(files, fileList);
      let formDatas = new FormData();
      formDatas.append('file', files["0"]);
      this.$http.post('/api/saveFile', formDatas).then(res => {
        if (res.data.msg == '保存成功') {
          this.form.pic = `http://api_dev.wanxikeji.cn/${res.data.data}`
        }
      })
    },
    // 限制文件传输数量
    handleExceed2(files, fileList) {
      this.handleRemove2(files, fileList);
      let formDatas = new FormData();
      formDatas.append('file', files["0"]);
      this.$http.post('/api/saveFile', formDatas).then(res => {
        if (res.data.msg == '保存成功') {
          this.changeform.pic = `http://api_dev.wanxikeji.cn/${res.data.data}`
        }
      })
      // this.$message.warning(
      //   `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length
      //   } 个文件`
      // );
    },
    // 上传到服务器
    submitUpload() {
      // this.$refs.upload.submit();
      let formData = new FormData();
      formData.append("file", this.imgfile);
      this.$http.post("/api/saveFile", formData).then((res) => {
        console.log(res.data.data);
        let imgUrl = "http://api_dev.wanxikeji.cn/" + res.data.data;
        console.log("imgUrl=", imgUrl);
        this.form.pic = imgUrl;
        // 获取token
        let token = sessionStorage.getItem("token");
        // 获取title
        let title = this.form.title;
        // 获取pic
        let pic = this.form.pic;
        // 获取describe
        let describe = this.form.describe;
        // 获取富文本的html
        let info = localStorage.getItem("info");
        console.log(info);
        // 通过接口添加数据
        this.$http
          .post("api/admin/worksAddModify", {
            token: token,
            title: title,
            pic: pic,
            describe: describe,
            info: info,
          })
          .then((res) => {
            console.log("添加数据", res);
            // 添加禁用按钮
            // this.forbidden.push("禁用");
            // 渲染数据
            this.drawing();
          });
      });
    },
    // 取消删除imgfile
    handleRemove(val, vals) {
      vals.splice(vals.length - 1, 1)
    },
    handleRemove2(val, vals) {
      vals.splice(vals.length - 1, 1)
    },
    // addimg() {
    //    let formData = new FormData();
    //   formData.append("img", this.imgfile);
    //    console.log("formData",formData);
    //    this.$http.post("/api/saveFile", formData).then((res) => {
    //     console.log(res.data.data);
    //    let imgUrl='http://api_dev.wanxikeji.cn/'+res.data.data
    //    console.log("imgUrl=",imgUrl);
    //    this.form.pic = imgUrl;
    //   });
    // },

    // 添加作品内容-富文本
    addrichtext() {
     

      // 检验表单是否填写完整
      if(!this.testForm(this.form)){
        return;
      }
      
      // 上传网上图片
      if (this.form.pic == "") {
        this.submitUpload();
      } else {
        // 获取token
        let token = sessionStorage.getItem("token");
        // 获取title
        let title = this.form.title;
        // 获取pic
        console.log("this.form.pic3", this.form.pic);
        let pic = this.form.pic;
        // 获取describe
        let describe = this.form.describe;
        // 获取富文本的html
        let info = localStorage.getItem("info");
        console.log(info);
        // 通过接口添加数据
        this.$http
          .post("api/admin/worksAddModify", {
            token: token,
            title: title,
            pic: pic,
            describe: describe,
            info: info,
          })
          .then((res) => {
            console.log("添加数据", res);
            // 渲染数据
            this.drawing();
          });
      }
       this.EDIshow = false;
      this.TABLEshow = true;
      let formData = "";
    },
    // 取消修改
    offchangetext() {
      this.EDIchange = false;
      this.TABLEshow = true;
    },
    // 渲染数据
    drawing() {
      
        this.dataShow = this.alldataShow;
    
    },

    // 提交修改
    changetext() {
      this.EDIchange = false;
      this.TABLEshow = true;
      if (this.changeform.pic == "") {
        // this.$refs.upload.submit();
        let formData = new FormData();
        formData.append("file", this.imgfile);
        this.$http.post("/api/saveFile", formData).then((res) => {
          console.log(res.data.data);
          let imgUrl = "http://api_dev.wanxikeji.cn/" + res.data.data;
          console.log("imgUrl=", imgUrl);
          this.changeform.pic = imgUrl;
          // 获取token
          let token = sessionStorage.getItem("token");
          // 获取title
          let title = this.changeform.title;
          // 获取pic
          let pic = this.changeform.pic;

          // 获取describe
          let describe = this.changeform.describe;
          // 获取id
          let id = this.changeform.id;
          // 获取富文本的html
          let info = localStorage.getItem("info");
          console.log("info", this.changeform.pic);
          // 通过接口修改数据
          this.$http
            .post("api/admin/worksAddModify", {
              token: token,
              title: title,
              pic: pic,
              describe: describe,
              info: info,
              id: id,
            })
            .then((res) => {
              console.log("修改后数据", res);
              // 渲染数据
              this.drawing();
            });
        });
      } else {
        // 获取token
        let token = sessionStorage.getItem("token");
        // 获取title
        let title = this.changeform.title;
        // 获取pic
        let pic = this.changeform.pic;

        // 获取describe
        let describe = this.changeform.describe;
        // 获取id
        let id = this.changeform.id;
        // 获取富文本的html
        let info = localStorage.getItem("info");
        console.log("info", this.changeform.pic);
        // 通过接口修改数据
        this.$http
          .post("api/admin/worksAddModify", {
            token: token,
            title: title,
            pic: pic,
            describe: describe,
            info: info,
            id: id,
          })
          .then((res) => {
            console.log("修改后数据", res);
            // 渲染数据
            this.drawing();
          });
      }
    },
    // 刷新
    refresh() {
      this.namesearch = "";
    },
    // 搜索数据
    searchdata() { },
    // selection删除
    selectionchange(value) {
      this.deleteall = value;
      console.log("this.deleteall==============", this.deleteall);
    },
    // 删除多条数据
    deletemore() {
      let maxpage = Math.ceil(this.alldataShow.length / this.pagesize);
      this.deleteall.forEach((element) => {
        // 获取token
        let token = sessionStorage.getItem("token");
        // 获取id
        let id = element.id;
        // 通过id删数据
        this.$http
          .post("api/admin/worksDelete", {
            token: token,
            id: id,
          })
          .then((res) => {
            console.log("删除多条数据", res);
            this.arraylength = this.alldataShow.length;
            // 渲染数据
            this.drawing();
          });
        // 截取禁用按钮
        // this.forbidden.forEach(element => {
        //   this.forbidden.splice(this.forbidden.indexOf(element),1)
        // });
      });
    },
    // 信息修改
    handleEdit(index, row) {
      console.log("row===", row);
      // 设置id数据
      localStorage.setItem("workId", JSON.stringify(row.id));
      this.EDIchange = !this.EDIchange;
      this.TABLEshow = !this.TABLEshow;
      this.changeform.id = row.id;
      this.changeform.title = row.title;
      this.changeform.pic = row.pic;
      this.changeform.describe = row.describe;
      // 数据索引
    },
    // 删除单条数据
    handleDelete(index, row) {
      // 获取token
      let token = sessionStorage.getItem("token");
      // 获取id
      let id = row.id;
      // 通过接口删除数据
      this.$http
        .post("api/admin/worksDelete", {
          token: token,
          id: id,
        })
        .then((res) => {
          console.log("删除数据", res);
          // 渲染数据
          this.drawing();
          // 截取禁用按钮
          //   this.forbidden.forEach(element => {
          //   this.forbidden.splice(this.forbidden.indexOf(element),1)
          // });
        });
    },
    // 分页器
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pagesize = val;
      // 渲染数据
      this.getWorksData();
    },

    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.page = val;
      this.currentPage4 = this.page;
      // 渲染数据
      this.getWorksData();
    },
    // 作品禁用
    forbiddendata(index, row) {
      // let i = this.alldataShow.indexOf(row);
      // this.forbidden[i] = "已禁用";
      console.log(row);
      // 获取token
      let token = sessionStorage.getItem("token");
      // 获取id
      let id = row.id;
      // 通过接口禁用数据
      this.$http
        .post("api/admin/worksBan", {
          token: token,
          id: id,
        })
        .then((res) => {
          console.log("禁用数据", res);
          // 渲染数据
          this.drawing();
        });
    },
    // handleSizeChange() {},
    // handleCurrentChange() {},
    // handleSelectionChange() {},
    testForm(form){

        if(form.title == ""){
          this.$message.info('缺少标题');
          return false;
        }
        if(form.pic == ""){
          this.$message.info('缺少图片');
          return false;
        }
        if(form.describe == ""){
          this.$$message.info('缺少描述');
          return false;
        }

        return true;
        
    },

    getWorksData(){
    var newdata = [];
    this.$http
      .post("api/admin/worksList", {
        token: this.token,
        page:this.page,
        size:this.pagesize,
      })
      .then((res) => {
        newdata = res.data.data.data;
        // 数组赋值
        this.alldataShow = [];
        newdata.forEach((element) => {
          var arr = { id: "", title: "", pic: "", describe: "", status: "" };
          arr.describe = element.describe;
          arr.pic = element.pic;
          arr.title = element.title;
          arr.id = element.works_id;
          arr.status = element.status;
          this.alldataShow.push(arr);
        });
        // this.alldataShow.reverse();
        // 根据id排序
        this.alldataShow.sort(function (a, b) {
          return a.id - b.id;
        });
       
        this.arraylength = res.data.data.count;
        this.drawing();
        // 添加禁用按钮
        // this.forbidden = Array(this.arraylength).fill("禁用");
        // console.log(this.alldataShow[0].status);
      });
  },
  },
  // 监听搜索框状态
  watch: {
    namesearch: {
      handler: function (newVal, oldVal) {
        // 修改radio
      },
      deep: true,
    },
    namesearch: {
      handler: function (newVal, oldVal) { },
      deep: true,
    },
  },
  
  mounted() {
    // 获取token
    this.token = sessionStorage.getItem("token");
    
    // 通过接口获取作品数据
    this.getWorksData();
  },
};
</script>

<style lang="less" scoped>
//
.top-btn {
  display: flex;
  /* height: 60px; */
}
.el-icon-refresh-left {
  display: flex;
  align-items: center;
}
.el-table .white {
  background: white;
}
.el-table .blue {
  background: rgb(18, 191, 235);
}
.el-table .red {
  background: rgb(236, 92, 66);
}
.el-table .purple {
  background: rgb(230, 108, 179);
}
.editorclass {
  padding: 0 50px 0 20px;
}
.editorform {
  display: flex;
  flex-direction: column;
  border: 2px solid #ccc;
  padding: 20px 10px 0 0;
}
.txtarea {
  width: 98%;
}
.title {
  display: flex;
  margin-bottom: 20px;
  justify-content: center;
}
.richbtn {
  width: 100%;
  padding: 0 40px;
  box-sizing: border-box;
  display: flex;
  justify-content: center;
}
// 公共table
/deep/.el-table__body-wrapper {
  font-size: 13px;
}
.container {
  min-height: 850px;
  background: #f6f6f6;
  padding-top: 20px;

  .table-data {
    padding: 0 20px;
  }

  .nav-top {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  /deep/.el-table td,
  /deep/.el-table th {
    text-align: center;
  }
  /deep/.el-form-item__label {
    width: 80px !important;
  }
  /deep/.el-input {
    width: 98%;
  }
  .editor{
    width: 100%;
    box-sizing:border-box;
    min-height: 30vh;
  }
  
.el-input{
  width: 100%;
}
.txtarea{
  width: 100%;
}
}
</style>
